(function(factory) {
if (typeof define === "function" && define.amd) {
	// AMD. Register as an anonymous module.
	define(factory);
} else {
	// Browser globals
	factory();
}
}(function() {
	/**
	 * @author 李球 <service@hteos.com>
	 * @class HteOS.window.Window 窗口组件
	 * @constructor
	 */
	var Window = HteOS.window.Window = function(options) {
		var win = this;
		win.id = "hte-window-" + options.id;
		var doc = $(document.body), docHeight = doc.height(),
			docWidth = doc.width();
		
		win.taskId = options.id;
		win.animateTarget = options.animateTarget;

		/**
		*@cfg
		*/
		win.width = 900;
		win.height = 500;
		win.maximizable = true;
		win.resizable = true;
		win.minHeight = 200;
		win.minWidth = 300;
		win.loadType = "iframe";
		win.maximized = false;
		win.animateCls = "hte-animate-2s"
		//添加属性
		HteOS.applyIf(win,{
			title: options.name,
			src: options.path,
			icon: options.icon,
			width : options.width > win.minHeight ? options.width : win.width,
			height : options.width > win.minHeight ? options.height : win.height,
			maximizable : options.maximizable,
			resizable : options.resizable,
			maximized : options.maximized || win.maximized,
			loadType : options.loadType || win.loadType
		});
		
		win.width = win.width > docWidth ? docWidth : win.width;
		win.heigt = win.height > docHeight ? docHeight : win.height;
		
		
		win.position = {
			left: (docWidth - win.width) / 2,
			top: (docHeight - win.height) / 2
		};
		
		//计算初始位置
		var position = {};
		if(options.bottom && options.bottom != 0){
			position.top = docHeight - win.height - options.bottom;
		}else if(options.top != 0){
			position.top = options.top;
		}
		if(options.right && options.right != 0){
			position.left = docWidth - win.width - options.right;
		}else if(options.left != 0){
			position.left = options.left;
		}
		
		//设置位置属性
		HteOS.applyIf(win.position,position);
		
		win.tpl = HteOS.Template.compile("<div class=\"hte-window hte-window-active "+ win.animateCls +"\">" 
				//+ "<div class=\"hte-window-preloader\"></div>" 
				+ "<div class=\"hte-window-cover\"></div>" 
				+ "<div class=\"hte-window-header\">" 
					+ "<span class=\"icon icon-windows\">" 
						+ "<img src=\"<%=icon%>\" >" 
						+ "</span>" 
					+ "<div class=\"title\"><%=title%></div>" 
					+ "<span class=\"btn-min\"></span>" 
					+ "<span class=\"btn-max\"></span>" 
					+ "<span class=\"btn-restore\"></span>" 
					+ "<span class=\"btn-close\"></span>"
				+ "</div>" 
				+ "<div class=\"hte-window-body\">" 
					//+ "<iframe frameborder=\"0\" dest=\"<%=src%>\"></iframe>" 
				+ "</div>"
			+"</div>");
		win.ghostTpl = HteOS.Template.compile("<div class=\"hte-window hte-window-dragging\">" + "<div class=\"hte-window-header\">" + "<span class=\"icon icon-windows\">" + "<img src=\"<%=icon%>\" >" + "</span>" + "<div class=\"title\"><%=title%></div>" + "</div>" + "</div>");

		win.proxyTpl = HteOS.Template.compile("<div class=\"hte-window hte-window-proxy\">" + "<div class=\"hte-window-header\">" + "<span class=\"icon icon-windows\">" + "<img src=\"<%=icon%>\" >" + "</span>" + "<div class=\"title\"><%=title%></div>" + "</div>" + "</div>");

		win.create();
	};
	
	Window.prototype.getEl = function() {
		return $("#" + this.id);
	};

	/**
	 * 关闭窗口，并触发窗口关闭事件;
	 */
	Window.prototype.close = function() {
		this.hide(true);
	};

	/**
	 * 将窗口展示在最前面
	 */
	Window.prototype.front = function() {
		if (this.hidden == true) {
			this.show();
		} else if (!this.active) {
			//激活窗口
			HteOS.window.WindowManager.setActive(this.id);
		}
	};

	/**
	 * 创建窗口，并触发创建窗口时间
	 */
	Window.prototype.create = function() {
		var win = this,
			el = $(win.tpl(win)),
			proxy = $(win.proxyTpl(win))
			container = HteOS.getContainer();
		// 设置css样式
		el.appendTo(container);
		proxy.attr("id", win.id + "-proxy");
		proxy.appendTo(container);
		if(this.maximizable === false){
			el.addClass("hte-window-unmaximize");
		}
		el.attr("id", win.id);
		var ghostTpl = win.ghostTpl;
		var attrs = {
			title: win.title,
			icon: win.icon
		};
		var winId = win.id;
		var ghostTpl = win.ghostTpl;
		// 初始化窗口拖动
		el.draggable({
			containment: container,
			helper: function() {
				var winEl = $("#" + winId);
				var ghost = $(ghostTpl(attrs)).appendTo(container);
				ghost.css({
					width: winEl.width(),
					height: winEl.height(),
					zIndex: winEl.css("z-index")
				});
				ghost.show();
				return ghost;
			},
			delay: 0,
			start: function(event, ui, instance) {
				el.hide();
			},
			stop: function(event, ui) {
				win.position = ui.position;
				win.lastStatus.top = win.position.top;
				win.lastStatus.left = win.position.left;
				el.css(ui.position);
				el.show();
			},
			handle: ".hte-window-header"
		});

		if(this.resizable === true){
			// 启动拖动改变大小的组件
			el.resizable({
				handles: "all",
				containment: container,
				minHeight : win.minHeight,
				minWidth : win.minWidth,
				start: function() {
					$(this).removeClass(win.animateCls);
					$(this).addClass("hte-window-resize");
				},
				stop: function(el, ui) {
					win.height = win.lastStatus.height = ui.size.height;
					win.width = win.lastStatus.width = ui.size.width;
					$(this).removeClass("hte-window-resize");
					$(this).addClass(win.animateCls);
				}
			});
		}

		var doc = $(document),
			width = win.width,
			height = win.height,
			docHeight = $(document).height(),
			docWidth = $(document).width();

		//获取窗口最后的位置，如果是初始化的窗口则居中显示
		win.lastStatus = {
			width: width,
			height: height
		};
		
		HteOS.apply(win.lastStatus,win.position);

		//初始化窗口的位置
		el.css(win.lastStatus);
		/**
		 * @event hte-window-create 窗口创建时触发
		 */
		// 触发窗口创建事件
		HteOS.EventManager.trigger("hte.window.create", win);
		win.show();
		if(win.maximized === true){
			win.maximize();
		}
	};
	
	/**
	 * 备份一个窗口组件，用于窗口推拽
	 */
	Window.prototype.ghost = function() {
		var ghost = el.clone();
		ghost.find(".hte-window-body").html("");
		ghost.addClass("hte-window-dragging");
		ghost.removeAttr("id");
		return ghost;
	};

	/**
	 * 切换窗口的尺寸，如果是最大化则还原，否则最大化
	 */
	Window.prototype.toggleSize = function() {
		if (this.maximized === true) {
			this.restore();
		} else {
			this.maximize();
		}
	};
	
	Window.prototype.refresh = function(path){
		this.path = path;
		this.load();
	}
	
	/**
	* 加载远程资源，根据loadType属性来进行不同方式的加载
	*/
	Window.prototype.load = function() {
		var me = this,el = this.getEl(),body = el.find(".hte-window-body");
		HteOS.Masker.mask(body,{
			msg : '正在加载...',
			modal : true
		});
		if(this.loadType == 'iframe'){
			if(me.loaded === true){
				var iframe = el.find("iframe"),contentWin = iframe[0].contentWindow;
				if(contentWin.HteApp){
					var HteApp = contentWin.HteApp;
					if(HteApp.blockOnRefresh === true){
						HteOS.Messager.confirm("提示",HteApp.blockText,function(btn){
							if(btn == 'yes'){
								doLoad();
							}else{
								HteOS.Masker.unmask(body);
							}
						});
					}else{
						doLoad();
					}
					/*contentWin.HteApp.refresh(this.path,function(){
						HteOS.Masker.unmask(body);
					});*/
				}else{
					doLoad();
				}
				
				function doLoad(){
					iframe.off("load");
					me.loading = true;
					iframe.attr("src",me.path);
					iframe.load(function() {
						HteOS.Masker.unmask(body);
						me.loaded = true;
						me.loading = false;
					});
				}
				
			}else{
				var iframe = $("<iframe frameborder=\"0\" src=\""+this.src+"\"></iframe>" );
				iframe.appendTo(body);
				//iframe.attr("src", iframe.attr("dest"));
				//el.find(".hte-window-preloader").show();
				// iframe加载后更改状态
				me.loading = true;
				iframe.load(function() {
					HteOS.Masker.unmask(body);
					el.addClass("hte-window-loaded");
					var win = iframe[0].contentWindow;
					if(win.HteApp){
						win.HteApp.setTaskId(me.taskId);
					}else{
						win.$HteTaskId = me.taskId;
					}
					//el.find(".hte-window-preloader").remove();
					me.loaded = true;
					me.loading = false;
				});
			}
		}else{
			me.loading = true;
			$.ajax({
				url : me.src,
				method : 'get',
				dataType : 'html',
				success : function(html){
					HteOS.Masker.unmask(body);
					body.html(html);
				},
				error : function(request,status,error){
					el.addClass("hte-window-loaded");
					HteOS.Masker.mask(body,{
						msg : '加载远程资源发生错误...',
						modal : true
					});
					
				},
				complete: function() {
					me.loading = false;
					me.loaded = true;
				}
			});
		}
			
	};

	/**
	 * 最大化窗口，并触发最大化事件
	 */
	Window.prototype.maximize = function() {
		var el = this.getEl();
		if (this.hidden) {
			this.show({
				animate : false
			});
		}
		this.front();
		el.addClass("hte-window-maximize");
		var pos = el.position();
		this.lastStatus = {
			left: pos.left,
			top: pos.top,
			width: el.width(),
			height: el.height()
		};
		el.css({
			left: 0,
			top: 0,
			width: '100%',
			height : $(document).height() - $(".hte-taskbar").height()
		});
		el.draggable("disable");
		if(this.resizable){
			el.resizable("disable");
		}
		this.maximized = true;
		/**
		 * @event hte-window-maximize 在窗口最大化的时候触发
		 */
		HteOS.EventManager.trigger("hte.window.maximize");
	};

	/**
	 * 还原窗口，并触发还原事件
	 */
	Window.prototype.restore = function() {
		var el = this.getEl();
		if (this.hidden) {
			this.show();
		}else{ 
			el.removeClass("hte-window-maximize");
			el.css(this.lastStatus);
			el.draggable("enable");
			if(this.resizable){
				el.resizable("enable");
			}
			this.maximized = false;
		}
		
		if(this.loaded == true){
			el.addClass("hte-window-loaded");
		}
		
		/**
		 * @event hte-window-restore 在窗口还原时触发
		 */
		HteOS.EventManager.trigger("hte.window.restore");
	};

	/**
	 * 显示窗口，并触发显示窗口事件
	 */
	Window.prototype.show = function(options) {
		var win = this,
			el = this.getEl(),
			body = el.find(".hte-window-body"),
			preloader = el.find(".hte-window-preloader"),
			proxy = $("#" + win.id + "-proxy");

		var animateTarget = win.animateTarget;
		var animate = true;
		if(options){
			animate = options.animate;
		}
		if(win.maximized == true){
			animate = false;
		}

		//如果需要开启窗口动画效果
		if (animateTarget && HteOS.UA.advance && animate) {
			//定位在任务栏起点
			proxy.css({
				width: animateTarget.width(),
				height: animateTarget.height(),
				left: animateTarget.offset().left,
				top: animateTarget.offset().top,
				opacity: 0
			});
			proxy.show();
			//过度到窗口的位置
			window.setTimeout(function() {
				proxy.css($.extend(true, win.lastStatus, {
					opacity: 1
				}));
			}, 10);
			window.setTimeout(function() {
				proxy.hide();
				el.show();
				load();
			}, 400);
		} else {
			el.show();
			load();
		}
		
		function load(){
			if (!win.loaded && win.loading !== true) {
				win.load();
			}
		}
		/**
		 * @event hte-window-show 窗口显示时触发
		 */
		HteOS.EventManager.trigger("hte.window.show", win);
		/* else {
			//preloader.show();
			el.addClass("hte-window-loaded");
		}*/
		this.hidden = false;
	};

	/**
	 * 隐藏窗口，并触发窗口隐藏事件;
	 * @param remove 是否要关闭窗口
	 */
	Window.prototype.hide = function(remove) {
		var win = this,
			el = win.getEl(),
			proxy = $("#" + win.id + "-proxy");
		el.hide();
		el.removeClass("hte-window-max").removeClass("hte-window-loaded");
		//窗口最后的位置
		var lastStatus = win.lastStatus;
		var animateTarget = win.animateTarget;
		//如果需要开启窗口动画效果
		if (animateTarget && HteOS.UA.advance && win.hidden == false) {
			proxy.css(lastStatus);
			proxy.show();
			window.setTimeout(function() {
					proxy.css({
						width: animateTarget.width(),
						height: animateTarget.height(),
						left: animateTarget.offset().left,
						top: animateTarget.offset().top,
						opacity: 0
					});
			}, 10);
		window.setTimeout(function() {
			proxy.hide();
			doHide();
		}, 400);
	} else {
		doHide();
	}

	function doHide() {
			win.hidden = true;
			win.active = false;
	
			// 触发窗口隐藏事件
			/**
			 * @event hte-window-hide 隐藏时触发事件
			 * @param {HteOS.window.Window} win
			 */
			HteOS.EventManager.trigger("hte.window.hide", win);
			if (remove === true) {
				// 触发窗口关闭事件
				/**
				 * @event hte-window-close 关闭时触发事件
				 * @param {HteOS.window.Window} win
				 */
				HteOS.EventManager.trigger("hte.window.close", win);
				var current = $.ui.ddmanager.current
				if (current) {
					if (current.bindings.attr("id") == win.id) {
						//释放拖拽的内存
						$.ui.ddmanager.current = null;
					}
				}
				el.draggable("destroy");
				if(win.resizable){
					el.resizable("destroy");
				}
				el.remove();
				proxy.remove();
			}
		}
	};

	Window.prototype.setSize = function(width,height){
		this.setWidth(width);
		this.setHeight(heigth);
	};
	
	Window.prototype.setWidth = function(width){
		this.width = width;
		this.getEl().width(width);
	};
	
	Window.prototype.setHeight = function(height){
		this.height = height;
		this.getEl().height(height);
	};
	
	Window.prototype.getWidth = function(){
		return this.width;
	};
	
	Window.prototype.getHeight = function(){
		return this.height;
	};
	
	Window.prototype.getPosition = function(){
		return this.lastStatus;
	};
	
	Window.prototype.setPosition = function(position){
		this.getEl().css(position);
	};

}));